import {
  LitElement,
  html,
  css
} from 'lit-element'
import './turn-mode'
/**
 * An example element.
 *
 * @slot - This element has a slot
 * @csspart button - The button
 */
export class tabMenu extends LitElement {
  static get styles() {
    return css `:host {
      display: flex;
      border: solid 1px gray;
      padding: 16px;
    }
    .tab-menu-container{
      display: flex;
      flex-direction: column;
      list-style: none;
      margin: 0;
      padding: 0;
      width: 100px;
      height: 100px;
      text-align: center;
      background-color: rgba(0,0,0,.2);
      color: #fff;
    }
    li{
      flex: 1;
      padding: 0 1em;
      cursor: pointer;
      border-bottom: 1px solid;
    }
    li:last-child{
      border-bottom: none
    }
    li:hover,
    li.active{
      background-color:rgba(0, 0, 0, 0.3);
    }
    .tab-menu-content{
      position: relative;
      flex: 1;
      height: 175px;
      padding: .5em 0 0 .5em;
      background-color: rgba(0,0,0,.2);
    }
    .mode-type{
      display: none;
    }
    .mode-type.active{
      display:block;
    }
    .mutil-box .row{
      display: flex;
      width: 400px;
      height: 20px;
      margin-bottom: 5px;
    }
    .mutil-box .row .column{
      position: relative;
      flex: 1;
      width: calc(100% - 5px);
      border: 1px solid;
      margin-right: 5px;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .mutil-box .row .column .delete{
      position: absolute;
      top: 0;
      right: 5px;
      display: none;
      cursor: pointer;
    }
    .mutil-box .row .column .delete.active{
      display: block;
    }
    .single-view{
      width: 200px;
      height: 140px;
      border: 1px solid;
      background-image: url('/screen/static/images/test.png');
      background-size: cover;
      color: #fff;
      font-size: 24px;
      text-indent: 8px;
    }
    .turn-box{
      display: flex;
      flex-wrap: wrap;
      width: 400px
    }
    .turn-box .box-item{
      position: relative;
      width: 90px;
      border: 1px solid;
      margin: 5px 5px 0 0;
    }
    .box-item .delete{
      position: absolute;
      top: 0;
      right: 5px;
      cursor: pointer;
    }
    .view-list{
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      flex-wrap: wrap;
      width: 435px;
      height: 174px;
      overflow: auto;
    }
    .view-item{
      position: relative;
      width: 130px;
      height: 70px;
      margin: 5px;
      background-size: cover;
      cursor: pointer;
    }
    .view-item-title{
      color: #fff;
      pointer-events: none;
    }
    .check{
      position: absolute;
      bottom: 0;
      right: 0;
      display: none;
      pointer-events: none;
    }
    .check.active{
        display: block;
        color: #fff;
      }
    `
  }
  static get properties() {
    return {
      menus: {
        type: Array
      },
      currentType: {
        type: String
      },

    }
  }

  constructor() {
    super()
    this.menus = [{
      name: '单屏模式',
      type: 'single'
    }, {
      name: '多屏模式',
      type: 'mutil'
    }, {
      name: '轮播模式',
      type: 'turn'
    }, {
      name: '主页',
      type: 'home'
    }];
    this.currentType = 'single';
    this.localMenu = {
      type: 'single',
      mutilList: [
        [{}, {}],
      ],
      turnList: [],
      rowValue: 1,
      columnValue: 2,
      turnTime: 10,
      single: {
        name: 'test0',
        url: '/screen/static/images/test.png'
      }
    }
    this.viewList = []
    for (let i = 0; i < 8; i++) {
      this.viewList.push({
        name: 'test' + i,
        url: '/screen/static/images/test.png'
      })
    }
  }

  get $viewList() {
    return this.renderRoot.querySelector('.view-list');
  }
  get $confirmButtons() {
    return this.renderRoot.querySelectorAll('.confirm-button');
  }
  get $mutilInputs() {
    return this.renderRoot.querySelectorAll('.mutil input');
  }
  get $turnMode() {
    return this.renderRoot.querySelector('turn-mode');
  }
  get $iframe() {
    return this.renderRoot.ownerDocument.querySelector('iframe');
  }
  _resetMutilBox() {
    this.localMenu.mutilList = [];
    for (let i = 0; i < this.localMenu.rowValue; i++) {
      this.localMenu.mutilList.push([])
      for (let j = 0; j < this.localMenu.columnValue; j++) {
        this.localMenu.mutilList[i].push({});
      }
    }
    this.requestUpdate();
  }
  _loadFrame(){
    this.$iframe.src = '/screen/flowStatics.html';
  }
  _initEvent() {
    // 视图点击事件
    this.$viewList.addEventListener('click', (e) => {
      if (e.target.dataset.value) {
        if (e.target.querySelector('.check.active')) {
          return
        };
        console.log('click', e.target)
        let currentValue = JSON.parse(e.target.dataset.value);
        switch (this.localMenu.type) {
          case 'single':
            this.localMenu.single = currentValue;
            break;
          case 'mutil':
            this.localMenu.mutilList.every((row, i) => {
              return row.every((column, j) => {
                if (column.name === undefined) {
                  this.localMenu.mutilList[i][j] = currentValue;
                  return false;
                }
                return true
              })
            });
            console.log(this.localMenu)
            break;
          case 'turn':
            this.localMenu.turnList.push(currentValue);
            this.$turnMode.requestUpdate();
            this.requestUpdate();
            break;
        }
      }
      // 使用手动触发更新视图
      this.requestUpdate();
    })
    // 第一个视图确认按钮事件
    this.$confirmButtons[0].addEventListener('click', (e) => {
      console.log(e.target);
      this._loadFrame();
      this._saveMenu();
    });
    // 第二个视图确认按钮
    this.$confirmButtons[1].addEventListener('click', (e) => {
      console.log(e.target);
      let rowValue = this.$mutilInputs[0].value;
      let columnValue = this.$mutilInputs[1].value;
      let len = rowValue * columnValue;
      let filterMulits = [];
      this.localMenu.mutilList.forEach(i => {
        i.forEach(j => {
          if (j.name !== undefined) {
            filterMulits.push(j);
          }
        })
      });
      if (filterMulits.length !== len) {
        return alert('当前分屏的视图未填充满');
      }
      this._saveMenu();
    });
    // 多屏模式下的行数
    this.$mutilInputs[0].addEventListener('blur', (e) => {
      let value = e.target.value;
      console.log(value)
      if (value === '') {
        return alert('行数不能为空值或者小数点');
      }
      if (value > 3) {
        e.target.value = 3;
        return alert('行数不能超过3行');
      }
      if (value < 0) {
        e.target.value = 1;
        return alert('行数不能低于1行')
      }
      if (this.localMenu.rowValue === value) {
        return
      }
      this.localMenu.rowValue = value;
      this._resetMutilBox();
    })
    // 多屏模式下的列数
    this.$mutilInputs[1].addEventListener('blur', (e) => {
      let value = e.target.value;
      console.log(value)
      if (value === '') {
        return alert('列数不能为空值或者小数点');
      }
      if (value > 4) {
        e.target.value = 4;
        return alert('列数不能超过4列');
      }
      if (value < 0) {
        e.target.value = 1;
        return alert('列数不能低于1列')
      }
      if (this.localMenu.columnValue === value) {
        return
      }
      this.localMenu.columnValue = value;
      this._resetMutilBox();
    })
  }
  _getCacheMenu() {
    let cacheMenu = localStorage.getItem('cacheMenu');
    if (cacheMenu) {
      this.localMenu = JSON.parse(cacheMenu);
    }
  }
  _renderMenu() {
    switch (this.localMenu.type) {
      case 'single':
        this.currentType = this.menus[0].type;
        break;
      case 'mutil':
        this.currentType = this.menus[1].type;
        this.$mutilInputs[0].value = this.localMenu.rowValue;
        this.$mutilInputs[1].value = this.localMenu.columnValue;
        break;
      case 'turn':
        this.currentType = this.menus[2].type;
        this.$turnInput.value = this.localMenu.turnTime;
        break;
    }
  }
  _saveMenu() {
    localStorage['cacheMenu'] = JSON.stringify(this.localMenu);
  }

  _changeType(type) {
    this.currentType = type;
    this.localMenu.type = type;
    this.requestUpdate();
  }
  _isChecked(item) {
    switch (this.localMenu.type) {
      case 'single':
        return this.localMenu.single.name === item.name
      case 'mutil':
        return this.localMenu.mutilList.some(row => row.some(column => column.name === item.name));
      case 'turn':
        return this.localMenu.turnList.filter(i => i.name === item.name).length !== 0;
    }
  }
  _deleteMutil(e) {
    const {
      index1,
      index2
    } = e.target.dataset
    this.localMenu.mutilList[index1][index2] = {};
    console.log(e.target.dataset);
    this.requestUpdate();
  }
  _deleteTurn(e) {
    const {
      index
    } = e.target.dataset;
    this.localMenu.turnList.splice(index, 1);
    this.requestUpdate();
  }
  connectedCallback() {
    super.connectedCallback();
    console.log('connectedCallback');
    this._getCacheMenu();
  }
  update() {
    super.update();
    console.log('update')
  }
  firstUpdated() {
    console.log('firstUpdated')
    this._initEvent();
    this._renderMenu();
  }
  render() {
    let mutilBox = ''
    for (let i = 0; i < this.localMenu.rowValue; i++) {
      mutilBox += '<div class="row">'
      for (let j = 0; j < this.localMenu.columnValue; j++) {
        mutilBox += `<div class="column"></div>`
      }
      mutilBox += '</div'
    }
    mutilBox = html `${mutilBox}`;
    return html `
      <ul class="tab-menu-container">
        ${this.menus.map(item => 
          html`<li 
          class="item ${this.currentType==item.type?'active':''}" 
          @click=${()=>{this._changeType(item.type)}}>
          ${item.name}
          </li>`)} 
      </ul>
      <div class="tab-menu-content">
        <div class="mode-type single ${this.currentType=='single'?'active':''}" >
        <header>
          <span>请选择展示的页面</span>
          <button class="confirm-button">确认</button>
        </header>
        <section>
          <div class="single-view" style="background-image: url(${this.localMenu.single.url})">
          ${this.localMenu.single.name}
          </div>
        </section>
      </div>
      <div class="mode-type mutil ${this.currentType=='mutil'?'active':''}">
        <header>
          <span>
            请选择分屏数量
          </span>
          <input type="number" placeholder="行" value="1"> * <input type="number" placeholder="列" value="2">
          <button class="confirm-button">确认</button>
        </header>
        <section class="mutil-box">
          ${this.localMenu.mutilList.map((row,i)=>{
            return html`<div class="row">${row.map((column,j)=>{
              return html`<div class="column">${column.name} 
                <span class="delete ${column.name?'active':''}" data-index1="${i}" data-index2="${j}" @click="${(e)=>this._deleteMutil(e)}">x</span></div>`
            })}</div>`
          })}
        </section>
      </div>
      <turn-mode .localMenu=${this.localMenu} .currentType=${this.currentType} style="display:${this.currentType==='turn'?'block':'none'}"></turn-mode>
        <div class="view-list">
        ${this.viewList.map(item=>{
          return html`<div class="view-item" style="background-image:url(${item.url})" data-value=${JSON.stringify(item)}>
          <div class="view-item-title">${item.name}</div>
          <div class="check ${this._isChecked(item)?'active':''}" >★</div>
        </div>`})}
        </div> 
      </div> 
    `
  }
}

window.customElements.define('tab-menu', tabMenu)